package com.bb.blog.activiti.cmd;

import org.activiti.bpmn.model.FlowElement;
import org.activiti.bpmn.model.Process;
import org.activiti.bpmn.model.SequenceFlow;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.impl.history.HistoryManager;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntityManager;


/**
 * 跳转命令
 */
public class JumpCmd implements Command<Void> {
    private final Process mainProcess;
    private final String taskId;
    private final String targetNodeId;
    private final String reason;
    /**
     * @param taskId       当前任务ID
     * @param targetNodeId 目标节点定义ID
     */
    public JumpCmd(String taskId, String targetNodeId, Process mainProcess, String reason) {
        this.taskId = taskId;
        this.targetNodeId = targetNodeId;
        this.mainProcess = mainProcess;
        this.reason = reason;
    }

    @Override
    public Void execute(CommandContext commandContext) {

        TaskEntityManager taskEntityManager = commandContext.getTaskEntityManager();
        HistoryManager historyManager = commandContext.getHistoryManager();

        TaskEntity currentTask = taskEntityManager.findById(this.taskId);
        ExecutionEntity execution = currentTask.getExecution();
        FlowElement flowElement = mainProcess.getFlowElement(this.targetNodeId);

        historyManager.recordActivityEnd(execution, reason);
        historyManager.recordTaskEnd(this.taskId, reason);
        taskEntityManager.delete(taskId);


        execution.setCurrentFlowElement(flowElement);
        commandContext.getAgenda().planContinueProcessOperation(execution);

        return null;
    }
}
